package com.xygood.netdisk;

import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.CookieManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.os.Build;

public class LoginActivity extends ActionBarActivity {
	private static final String TAG = "LoginActivity";
	private static final String LOGIN_URL = "http://wappass.baidu.com/passport?login&authsite=1&tpl=netdisk&display=mobile&u=http%3A%2F%2Fyun.baidu.com%2F";
	
	private static final String PREF_NAME = "LoginPref";
	private static final String PREF_BAIDU_COOKIE = "baidu_cookie";
	
	private WebView mWebView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		mWebView = (WebView) findViewById(R.id.web);
		
		WebSettings webSettings = mWebView.getSettings();
		webSettings.setJavaScriptEnabled(true);
		
		mWebView.loadUrl(LOGIN_URL);
		mWebView.setWebViewClient(new WebViewClient() {
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				view.loadUrl(url);
				return true;
			}

		/*@Override
			public void onLoadResource(WebView view, String url) {
				if (url.equalsIgnoreCase("http://yun.baidu.com/wap/home")) {
					view.loadUrl("http://pan.baidu.com/disk/home?adapt=pc");
				}
			}*/
			@Override
			public void onPageFinished(WebView view, String url) {
				CookieManager cookieManager = CookieManager.getInstance();
				cookieManager.setAcceptCookie(true);
				String CookieStr = cookieManager.getCookie(url);
				Log.e(TAG, "url = " + url);
				Log.e(TAG, "Cookies = " + CookieStr);
				SharedPreferences settings = getSharedPreferences(PREF_NAME, 0);
				settings.edit().putString(PREF_BAIDU_COOKIE, CookieStr).commit();
				if (url.equalsIgnoreCase("http://yun.baidu.com/wap/home")) {
					finish();
				}
				
				 //CookieStr = cookieManager.getCookie("http://pan.baidu.com/api/");
				//Log.e(TAG, "pan.baidu Cookies = " + CookieStr);
				super.onPageFinished(view, url);
			}
		});
	}

}
